import { useState, useEffect } from 'react';

/**
 * 本地存储Hook - 自动同步状态与localStorage
 * @param {string} key - 存储键名
 * @param {any} initialValue - 初始值
 * @returns {[value, setValue]} - 返回值和设置函数
 */
export const useLocalStorage = (key, initialValue) => {
    // 从localStorage读取初始值
    const [storedValue, setStoredValue] = useState(() => {
        try {
            const item = window.localStorage.getItem(key);
            return item ? JSON.parse(item) : initialValue;
        } catch (error) {
            console.error(`读取localStorage失败:`, error);
            return initialValue;
        }
    });

    // 设置值并更新localStorage
    const setValue = (value) => {
        try {
            // 允许传入函数来更新值
            const valueToStore = value instanceof Function ? value(storedValue) : value;
            setStoredValue(valueToStore);
            window.localStorage.setItem(key, JSON.stringify(valueToStore));
        } catch (error) {
            console.error(`保存到localStorage失败:`, error);
        }
    };

    return [storedValue, setValue];
};

/**
 * 会话存储Hook - 自动同步状态与sessionStorage
 * @param {string} key - 存储键名
 * @param {any} initialValue - 初始值
 */
export const useSessionStorage = (key, initialValue) => {
    const [storedValue, setStoredValue] = useState(() => {
        try {
            const item = window.sessionStorage.getItem(key);
            return item ? JSON.parse(item) : initialValue;
        } catch (error) {
            console.error(`读取sessionStorage失败:`, error);
            return initialValue;
        }
    });

    const setValue = (value) => {
        try {
            const valueToStore = value instanceof Function ? value(storedValue) : value;
            setStoredValue(valueToStore);
            window.sessionStorage.setItem(key, JSON.stringify(valueToStore));
        } catch (error) {
            console.error(`保存到sessionStorage失败:`, error);
        }
    };

    return [storedValue, setValue];
};
